<?php

namespace app\api\controller;

use app\api\validate\ValidateMechanism;
use app\common\controller\Api;
use app\common\model\User as Model;
use app\api\validate\ValidateUser;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Loader;
use think\Request;
use think\Session;

class User
{
    protected $validate;
    protected $data;
    private $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * 新增用户
     * @throws \think\Exception
     */
    public function add()
    {
        $request = $this->request;
        $data    = $request->param();

        $data['p_u_id']    = Session::get('userinfo.u_id');
        $data['u_account'] = $this->getNewAccount();

        # 验证参数
        $validate = $this->getValidate();
        $result   = $validate->scene('add')->check($data);

        if ($result) {
            $model = new Model();
            # 判断是否已经存在用户名
            $where = [
                'u_name'   => $data['u_name'],
                'u_status' => ['neq', '-1']
            ];

            $has = $model->where($where)->find();
            if ($has) Api::returnJson('500', [], '该用户名已经存在');

            $res = $model->addUser($data);
            if ($res) {
                $returnData = [
                    'u_account' => $data['u_account'],
                    'u_name'    => $data['u_name'],
                ];
                Api::returnJson('200', $returnData, '新增成功');
            }
            Api::returnJson('500', [], '新增失败');
        }
        Api::returnJson('400', [], '参数错误:' . $validate->getError());
    }

    /**
     * 數據編輯
     * @throws \think\Exception
     */
    public function edit()
    {
        $request = $this->request;
        $data    = $request->param();

        # 验证参数
        $validate = $this->getValidate();
        $result   = $validate->scene('edit')->check($data);
        $userData['data'] = $data;
        $userData['where'] = array('u_id'=>$data['ids']);

        if ($result) {
            $model = new Model();
            $res = $model->editUser($userData);

          if($res){
                Api::returnJson('200',[],lang('Operation is successful'));
            }

            Api::returnJson('500',[],lang('The operation failure'));
        }

        Api::returnJson('400', [], '参数错误:' . $validate->getError());
    }


    /**
     * 修改密碼
     * @throws \think\Exception
     */
    public function editPwd()
    {
        $request = $this->request;
        $data    = $request->param();

        # 验证参数
        $validate = $this->getValidate();
        $result   = $validate->scene('pwd')->check($data);
        $userData['data'] = $data;
        $userData['where'] = array('u_id'=>$data['ids']);

        if ($result) {
            $model = new Model();
            $res = $model->editUser($userData);

            if($res){
                Api::returnJson('200',[],lang('Operation is successful'));
            }

            Api::returnJson('500',[],lang('The operation failure'));
        }

        Api::returnJson('400', [], '参数错误:' . $validate->getError());
    }


    /**
     * 获取用户列表
     * @throws
     */
    public function getList()
    {
        $model = new Model();

        $request = $this->request;
        $data    = $request->param();

        $where = [
            'u_status'=>['neq','-1']
        ];

        $uId = $data['u_id'];

        $userModel       = new \app\common\model\User;
        $commomAuthClass = \app\common\controller\Auth::instance();

        $uInfo     = $userModel->field('role_id')->where(['u_id' => $uId])->find();


        empty($data['u_account']) or $where['u_account'] = $data['u_account']; // 指定搜索登录账号

        $this->data['where'] = $where;
        $this->data['field'] = 'u.u_id,u.u_name,u.u_account,u.p_u_id,u.role_id,u.u_status,u.create_time,u.update_time,r.role_name';
        $this->data['limit'] = $data['limit'];
        $this->data['page']  = $data['page'];
        $this->data['alias'] = 'u';
        $this->data['join']  = array(
            ['role r','r.id = u.role_id','left'],
            );
        $return = $model->getList($this->data);
        $count  = $model->where($this->data['where'])->count();
        if ($return) Api::returnJson('0', $return, $count);
        Api::returnJson('500', [], '数据异常或为空');
    }

    /**
     * 获取验证器
     * @return ValidateUser
     */
    private function getValidate()
    {
        return !empty($this->validate) ? $this->validate : new ValidateUser();
    }

    /**
     * 获取新用户id
     * @return string 新增用户id
     * @throws \think\Exception
     */
    private function getNewAccount()
    {
        # 读取数据库id并拼接随机一个字符
        $tem = Db::name('system')->where('id', 1)->find();

        Db::name('system')->where('id', 1)->setInc('user_id');

        return $tem['user_id'] . rand(10, 99);
    }


    //openid => url
    // pay => url


    /**
     * 用户登录
     * @throws \think\Exception
     */
    public function login()
    {
        $request = $this->request;
        $model   = new Model();

        $userAccount = $request->param('useraccount');
        $passWord    = $request->param('password');

        $has = $model->where('u_account', $userAccount)
            ->where('u_status', 'neq', '-1')
            ->field('u_account,u_name,u_password,u_id,p_u_id,role_id,u_status')
            ->find();

        if (!$has) Api::returnJson('500', [], '用户不存在');

        if ($has['u_password'] !== $passWord) Api::returnJson('501', [], '密码错误');

        if ($has['u_status'] == '0') Api::returnJson('502', [], '用户已被禁用，请联系管理员');

        Session::set('userinfo', $has);
        Api::returnJson('200', [], '登录成功');
    }

    /**
     * 用户退出登录
     */
    public function logout()
    {
        Session::set('userinfo', null);
    }

    /**
     * 用户删除
     * @throws
     */
    public function del()
    {
        # 验证权限（未写）

        # 删除
        $uId = $this->request->param('u_id');

        $model = new Model();

        $res = $model->del($uId);

        if ($res) {
            Api::returnJson('200', [], '删除成功');
        }
        Api::returnJson('500', [], '删除失败');
    }
}
